package com.enzyun;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.util.concurrent.CountDownLatch;

@SpringBootApplication
public class TestApplication implements CommandLineRunner {

	public static void main(String[] args) {
		SpringApplication.run(TestApplication.class, args);
	}

	@Override
	public void run(String... strings) throws Exception {
			//1.第一个线程组管理client端连接
			EventLoopGroup bossGroup = new NioEventLoopGroup();
			//2.第二个线程组处理实际业务操作
			EventLoopGroup workerGroup = new NioEventLoopGroup();
			//3.创建辅助类，对server进行配置
			ServerBootstrap bootstrap = new ServerBootstrap();
			//4.把工作线程加入到bootstrap中
			bootstrap.group(bossGroup, workerGroup)
					//5.指定使用NioServerSocketChannel类型的通道
					.channel(NioServerSocketChannel.class)
					//日志级别
					.handler(new LoggingHandler(LogLevel.ERROR))
					//6.使用childHandler绑定具体的事件处理器
					.childHandler(new ChannelInitializer<SocketChannel>() {
						@Override
						protected void initChannel(SocketChannel socketChannel) throws Exception {
							socketChannel.pipeline().addLast(new ServerHandler());
						}
					}).option(ChannelOption.SO_BACKLOG, 128)//设置tcp缓冲区
					.childOption(ChannelOption.SO_KEEPALIVE, true);//保持连接
			//7.绑定指定的端口并监听
			ChannelFuture future = bootstrap.bind(6688).sync();
		}
	}
